package com.headfirst.observer.version2;

import com.headfirst.observer.version1.DisplayElement;
import com.headfirst.observer.version1.Subject;

import java.util.Observable;
import java.util.Observer;

/**
 * @author sunhongguang
 * @create 2022-01-18-23:57
 */
public class StatisticsDisplay_v2 implements Observer, DisplayElement {

    private float maxTemperature = 0.0f;
    private float minTemperature = 200f;
    private float temperatureSum = 0.0f;
    private int numReadings;
    private Observable observable;

    public StatisticsDisplay_v2(Observable observable) {
        this.observable = observable;
        observable.addObserver(this);
    }

    @Override
    public void update(Observable o, Object arg) {
        if(o instanceof WeatherData_v2){
            WeatherData_v2 weatherDataV2 = (WeatherData_v2)o;
            float temp = weatherDataV2.getTemperature();
            temperatureSum += temp;
            numReadings++;
            if(temp > maxTemperature){
                maxTemperature = temp;
            }
            if(temp < minTemperature){
                minTemperature = temp;
            }
            display();
        }
    }

    @Override
    public void display() {
        System.out.println("Avg/Max/Min temperature = "+(temperatureSum/numReadings)+"/"+maxTemperature+"/"+minTemperature);
    }
}
